<template>
  <AuModal
    v-model="showDetailModal"
    :title="title"
    width="812"
    height="auto"
    :padding="false"
    @close="close"
    @handleConfirm="handleConfirm"
  >
    <!--    <div class="py-[16px] px-[20px] border-b-[1px] border-[#EAEBEF]">-->
    <!--      <AuForm-->
    <!--        ref="formRef"-->
    <!--        class="formula-form"-->
    <!--        :formList="formList"-->
    <!--        :hiddenBtn="true"-->
    <!--        :formData="formData"-->
    <!--      />-->
    <!--    </div>-->

    <el-scrollbar ref="scrollRef" wrap-class="p-[20px]" style="height: 60vh">
      <div
        v-for="(step, index) in cleanStep"
        :key="index"
        class="bg-[#F5F9FF] rounded-[2px] px-[16px] py-[20px] mt-[16px] first:mt-0"
      >
        <div class="flex justify-between">
          <div class="text-[#242930] text-[14px]">
            {{ t("device_manage.clean.step", { index: index + 1 }) }}
          </div>
          <el-button
            link
            class="!text-[#EA2626] !text-[12px] !hover:text-[#ea4949]"
            @click="removeStep(index)"
          >
            <component
              :is="useRenderIcon(Delete)"
              class="text-[12px] ml-1 mt-[1px]"
            />
            <span class="inline-block align-middle"
              >&nbsp;{{ t("buttons.delete") }}</span
            >
          </el-button>
        </div>

        <div class="mt-[20px]">
          <el-form
            ref="stepFormRef"
            :model="step"
            :rules="stepRules"
            class="formula-inForm"
            inline
            label-width="120px"
          >
            <el-form-item
              :label="t('device_manage.clean.clean_medium')"
              prop="type"
            >
              <AuSelect
                v-model="step.type"
                :placeholder="t('device_manage.clean.select_clean_medium')"
                :options="CLEAN_MEDIUM_LIST"
                valueKey="id"
                labelKey="name"
                style="width: 200px"
              />
            </el-form-item>
            <el-form-item
              :label="t('device_manage.clean.clean_type')"
              prop="clean_type"
            >
              <AuSelect
                v-model="step.clean_type"
                :placeholder="t('device_manage.clean.select_clean_type')"
                :options="CLEAN_TYPE_LIST"
                valueKey="id"
                labelKey="name"
                style="width: 200px"
              />
            </el-form-item>
            <el-form-item
              :label="t('device_manage.clean.clean_time')"
              prop="time"
            >
              <vxe-input
                v-model="step.time"
                min="0"
                type="integer"
                :placeholder="t('device_manage.clean.enter_clean_time')"
                style="width: 200px"
              >
                <template #suffix>
                  <span>{{ t("device_manage.clean.seconds") }}</span>
                </template>
              </vxe-input>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </el-scrollbar>

    <div class="text-center my-2 px-[20px]">
      <el-button
        class="w-full !h-[46px] !text-[--el-color-primary] font-[500] !text-[14px] disabled:!text-[--autata-font-gray-color]"
        color="#F5F9FF"
        :disabled="cleanStep.length < 0"
        @click="addStep"
      >
        <FontIcon icon="icon-plus2" /> &nbsp;
        {{ t("device_manage.clean.add_step") }}
      </el-button>
    </div>
  </AuModal>
</template>

<script setup lang="ts">
import { AuForm, AuSelect } from "@/components/AuForm";
import { AuModal } from "@/components/AuModal";
import { computed, nextTick, onMounted, ref, watch } from "vue";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import Delete from "@/assets/svg/delete.svg?component";
import {
  deviceCleanStepAdd,
  deviceCleanStepUpd,
  getListModelByComponent
} from "@/api/cabinet/device";
import { ElMessage } from "element-plus";
import { useI18n } from "vue-i18n";

const { t } = useI18n();

const props = defineProps<{
  modelValue: boolean;
  rowData: any;
}>();
const emit = defineEmits(["update:modelValue", "confirm"]);

const showDetailModal = computed({
  get() {
    return props.modelValue;
  },
  set(value) {
    emit("update:modelValue", value);
  }
});

const CLEAN_MEDIUM_LIST = [
  {
    id: 1,
    name: "清水"
  },
  {
    id: 2,
    name: "清洁剂"
  },
  {
    id: 3,
    name: "消毒液"
  },
  {
    id: 4,
    name: "空气"
  }
];
const CLEAN_TYPE_LIST = [
  {
    id: 1,
    name: "冲洗"
  },
  {
    id: 2,
    name: "浸泡"
  }
];

const formList = ref([
  {
    type: "select",
    key: "device_model",
    label: "device_manage.form.device_model",
    placeholder: "device_manage.form.device_model_placeholder",
    valueKey: "device_model",
    labelKey: "device_model",
    required: true,
    filterable: true,
    span: 8,
    options: []
  },
  {
    type: "select",
    key: "type_id",
    label: "device_manage.form.device_status",
    placeholder: "device_manage.form.device_status_placeholder",
    valueKey: "id",
    labelKey: "name",
    filterable: true,
    span: 8,
    options: [
      { id: 1, name: "营业" },
      { id: 2, name: "打烊" }
    ]
  }
]);
const formData = ref({});
const title = ref("");
const formRef = ref();
const stepFormRef = ref();
const scrollRef = ref();

const cleanStep = ref([
  {
    type: 1,
    clean_type: 1,
    time: ""
  }
]);

const stepRules = ref({
  type: [
    {
      required: true,
      message: t("device_manage.clean.clean_medium_required"),
      trigger: "change"
    }
  ],
  clean_type: [
    {
      required: true,
      message: t("device_manage.clean.clean_type_required"),
      trigger: "change"
    }
  ],
  time: [
    {
      required: true,
      message: t("device_manage.clean.clean_time_required"),
      trigger: "blur"
    }
  ]
});

const removeStep = (index: number) => {
  if (cleanStep.value.length === 1) {
    ElMessage.warning(t("device_manage.clean.keep_one_step"));
    return;
  }
  cleanStep.value.splice(index, 1);
};
const addStep = () => {
  cleanStep.value.push({
    type: 1,
    clean_type: 1,
    time: ""
  });
};

const getDeviceList = () => {
  getListModelByComponent({ size: 0, device_type: "柜式机" }).then(res => {
    const data = [];
    for (const item of res.data) {
      if (!data.find(v => v.device_model == item.device_model)) {
        data.push(item);
      }
    }
    formRef.value.setFormProps("device_model", { options: data });
  });
};

const handleConfirm = async () => {
  let checkIndex = 0;
  for (const ele of stepFormRef.value) {
    try {
      await ele.validate();
      checkIndex++;
    } catch (e) {
      scrollRef.value.setScrollTop(checkIndex * 183);
      return;
    }
  }

  let service = deviceCleanStepAdd;
  const param = {
    id: null,
    type_id: 1,
    clean_step: JSON.stringify(
      cleanStep.value.map((v, i) => ({ ...v, index: i + 1 }))
    ),
    clean_type: "半自动"
  };
  if (props.rowData?.id) {
    service = deviceCleanStepUpd;
    param.id = props.rowData.id;
    param.type_id = props.rowData.type_id;
  }
  service(param).then(() => {
    close();
    emit("confirm");
  });
};

const close = () => {
  emit("update:modelValue", false);
};

watch(
  () => [showDetailModal.value, props.rowData],
  ([val, row]: [boolean, any]) => {
    if (val) {
      title.value = row?.id
        ? t("device_manage.clean.edit_title")
        : t("device_manage.clean.add_title");
      if (row?.clean_step) {
        cleanStep.value = JSON.parse(row?.clean_step);
        if (!cleanStep.value.length) {
          addStep();
        }
      }
      nextTick(async () => {});
    } else {
      cleanStep.value = [
        {
          type: 1,
          clean_type: 1,
          time: ""
        }
      ];
    }
  }
);

onMounted(() => {});
</script>
